package org.xuyuji.demo.xstream.tools;

import com.thoughtworks.xstream.XStream;
import com.thoughtworks.xstream.io.xml.DomDriver;

public class XmlUtil {

	public static String toXml(Object obj){
		//指定编码解析器,直接用jaxp dom来解释
		XStream xstream=new XStream(new DomDriver("utf-8"));
		
		//如果没有这句，xml中的根元素会是<包.类名>；或者说：注解根本就没生效，所以的元素名就是类的属性
		xstream.processAnnotations(obj.getClass());
		
		//去除class节点
		xstream.aliasSystemAttribute(null, "class");
		
		return xstream.toXML(obj);
	}
	
	@SuppressWarnings("unchecked")
	public static <T> T  toBean(String xmlStr,Class<T> cls){
		//注意：不是new Xstream(); 否则报错：java.lang.NoClassDefFoundError: org/xmlpull/v1/XmlPullParserFactory
		XStream xstream=new XStream(new DomDriver("utf-8"));
		
		//使用注释
		xstream.processAnnotations(cls);
		
		//忽略多余的xml元素，没有的话，必须一一对应，否则会报错
		xstream.ignoreUnknownElements();
		
		T obj = (T)xstream.fromXML(xmlStr);
		return obj;			
	} 

}
